/**
 * 图片压缩适配器
 * 解决不同环境下的导入和使用问题
 */

let compressInstance = null

// #ifdef H5
// H5环境：使用 Canvas 压缩
const compressH5 = (filePath, options = {}) => {
  return new Promise(async (resolve, reject) => {
    console.log('H5 压缩开始:', { filePath, options })
    
    try {
      const img = new Image()
      img.crossOrigin = 'anonymous'
      
      // 设置超时
      const timeout = setTimeout(() => {
        console.error('图片加载超时')
        reject(new Error('图片加载超时'))
      }, 10000)
      
      img.onload = () => {
        clearTimeout(timeout)
        console.log('图片加载完成:', { width: img.width, height: img.height })
        
        try {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          
          // 设置压缩尺寸 - 限制最大尺寸以避免内存问题
          let { width, height } = options
          const maxSize = 1920 // 最大尺寸限制
          
          if (!width && !height) {
            width = img.width
            height = img.height
            
            // 如果图片太大，按比例缩小
            if (width > maxSize || height > maxSize) {
              const scale = Math.min(maxSize / width, maxSize / height)
              width = Math.round(width * scale)
              height = Math.round(height * scale)
            }
          } else if (width && !height) {
            height = Math.round((img.height * width) / img.width)
          } else if (!width && height) {
            width = Math.round((img.width * height) / img.height)
          }
          
          console.log('压缩目标尺寸:', { width, height })
          
          canvas.width = width
          canvas.height = height
          
          // 绘制图片
          ctx.fillStyle = '#fff'
          ctx.fillRect(0, 0, width, height)
          ctx.drawImage(img, 0, 0, width, height)
          
          console.log('开始转换为blob...')
          
          // 转换为blob
          canvas.toBlob((blob) => {
            console.log('Blob转换结果:', blob)
            if (blob) {
              console.log('压缩完成，原始大小:', img.src.length, '压缩后大小:', blob.size)
              const url = URL.createObjectURL(blob)
              resolve(url)
            } else {
              console.error('Blob转换失败')
              reject(new Error('压缩失败：无法生成blob'))
            }
          }, 'image/jpeg', options.quality || 0.8)
          
        } catch (canvasError) {
          console.error('Canvas处理错误:', canvasError)
          reject(canvasError)
        }
      }
      
      img.onerror = (error) => {
        clearTimeout(timeout)
        console.error('图片加载失败:', error)
        reject(new Error('图片加载失败'))
      }
      
      console.log('开始加载图片:', filePath)
      img.src = filePath
      
    } catch (error) {
      console.error('压缩过程出错:', error)
      reject(error)
    }
  })
}

compressInstance = (paths, options = {}) => {
  return new Promise(async (resolve, reject) => {
    try {
      const results = []
      for (const path of paths) {
        const result = await compressH5(path, options)
        results.push(result)
      }
      resolve(results)
      options.success && options.success(results)
    } catch (error) {
      reject(error)
      options.fail && options.fail(error)
    }
  })
}
// #endif

// #ifndef H5
// 非H5环境：使用uni.compressImage
compressInstance = (paths, options = {}) => {
  return new Promise(async (resolve, reject) => {
    try {
      const results = []
      
      for (const path of paths) {
        const result = await new Promise((res, rej) => {
          uni.compressImage({
            src: path,
            compressedWidth: options.width,
            compressedHeight: options.height,
            quality: (options.quality || 0.8) * 100,
            success: (compressResult) => {
              res(compressResult.tempFilePath)
            },
            fail: rej
          })
        })
        results.push(result)
      }
      
      resolve(results)
      options.success && options.success(results)
    } catch (error) {
      reject(error)
      options.fail && options.fail(error)
    }
  })
}
// #endif

export default compressInstance
